'use strict';

const BaseService = require('../library/base-service');
const UserMapper = require("../database/mapper/user");
const GameMapper = require("../database/mapper/game");
const FinanceBo = require("../bo/finance-bo");
const LoginBo = require("../bo/login-bo");
const WeChatMapper = require("../database/mapper/wechat");


/**
 * 示例服务（service层为单例）
 * @class
 */
class UserService extends BaseService {

    init() {
        this.mapper = new UserMapper()
    }

    async getBalance(uid) {
        /** @type {FinanceBo}*/
        let finance = await this.getFinanceInstance(uid)
        let balance = await finance.getBalance()
        await this.mapper.save({
            balance: balance
        }, {
            id:uid,
        })
        return {
            balance: await finance.getBalance()
        }
    }

    async getRecords(uid) {
        /** @type {FinanceBo}*/
        let finance = await this.getFinanceInstance(uid)
        let {records,total_money} = await finance.calculateUserMoney()
        await this.mapper.save({
            'total_money': total_money
        }, {id: uid})
        return records
    }

    async withdraw(uid, money) {
        /** @type {FinanceBo}*/
        let finance = await this.getFinanceInstance(uid)
        return finance.withdraw(money)
    }

    async getFinanceInstance(uid) {
        let user = await this.mapper.read(uid)
        let roleInfo = user.role_fmt_info
        let financeBo = new FinanceBo(roleInfo.game_id, roleInfo.server_id, roleInfo.role_id, roleInfo.user_name)
        return financeBo.setDeviceInfo(user.device).setClientIp(user.client_ip).setCookies(user.cookies)
    }

    async login(uid) {
        let user = await this.mapper.read(uid)
        let gameMapper = new GameMapper()
        let game = await gameMapper.find({where: {id: user.game_id}})
        let loginBo = new LoginBo(user, game)

        let res1 = await loginBo.doLoginToGame()

        let res2 = await loginBo.getUserInfo()

        let res3 = await loginBo.doLoginToLottery()

        return res1 && res2 && res3

    }

    async updateUserMoney() {
        let users = await this.mapper.getList()

        for (const user of users) {
            if (!user['role_info']) {
                continue
            }
            //不充值的不查询
            if (user['recharge_money'] <= 0) {
                continue
            }

            /** @type {FinanceBo}*/
            let finance = await this.getFinanceInstance(user['id'])
            let money_record = await finance.calculateUserMoney()

            await this.mapper.save({
                'total_money': money_record['total_money'],
                'balance': money_record['balance'],
            }, {id: user['id']})
        }

        return true;
    }

    async benefitsList() {
        let users = await this.mapper.getList();
        let gameMapper = new GameMapper()
        let games = await gameMapper.getList();
        let gameObj = {};
        games.forEach(game => {
            gameObj[game['id']] = game['name'];
        })

        let wechatMapper = new WeChatMapper()
        let weChats = await wechatMapper.getList();
        let weChatObj = {};
        weChats.forEach(wechat => {
            weChatObj[wechat['id']] = wechat;
        })

        let res = [];
        users.forEach((item, index) => {
            if (item['recharge_money'] <= 0) {
                return;
            }
            const wx_name = weChatObj[item['wx_id']] ? weChatObj[item['wx_id']]['nickname'] : '';
            const owner = weChatObj[item['wx_id']] ? weChatObj[item['wx_id']]['owner'] : '';
            res.push({
                'id': item['id'],
                'name': item['username'],
                'game_name': gameObj[item['game_id']],
                'wx_name': wx_name,
                'owner': owner,
                'recharge_money': item['recharge_money'],
                'income': item['total_money'],
                'withdrawn': parseFloat((item['total_money'] - item['balance']).toFixed(2)),
                'undelivered': item['balance'],
                'cookies_obj': item['cookies_obj'],
            })
        })

        return res;
    }


}

module.exports = UserService;